package models;

import java.util.List;

import javax.persistence.*;

import com.avaje.ebean.Page;
import com.avaje.ebean.validation.NotNull;

import play.db.ebean.Model;
import play.db.ebean.Model.Finder;

@Entity
public class Forest extends Model{
	
	@Id
	public Long id;
	
	@NotNull
	public String forestKey;
	
	@NotNull
	public Integer plotRadius;
	
	//Finder
	public static Finder<Long, Forest> find = new Finder<Long, Forest>(
			Long.class, Forest.class);
	
	public static Forest getForest(Forest forest) {
		return find.where().idEq(forest.id).findUnique();
//		return find.fetch("forest").where().idEq(forest.id).findUnique();
	}
	
    /**
     * Return a page of Forest
     *
     * @param page Page to display
     * @param pageSize Number of computers per page
     * @param sortBy Computer property used for sorting
     * @param order Sort order (either or asc or desc)
     * @param filter Filter applied on the name column
     */
	
    public static Page<Forest> page(int page, int pageSize, String sortBy, String order, String filter) {
        return 
            find.where()
                .ilike("name", "%" + filter + "%")
                .orderBy(sortBy + " " + order)
                .findPagingList(pageSize)
                .getPage(page);
    }
    
    /* 算法 */
    /*
     *总蓄积量算法
     *单位面积蓄积量
     *地位级
     *郁闭度
     *面积
     */
    
    /*未完成
     *
     */
    public Float volume(){
    	List<Compartment> compartment = Compartment.find.where().eq("compartment", this).findList();
    	Float volume = 0F;
    	for( int i = 0; i < compartment.size(); i++ ){
    		volume += compartment.get(i).volume();
    	}
    	return volume;
    }
    
    public Float volumePerHa(){
    	return this.volume()/this.area();
    }
    
    public Float canopyDensity(){
    	//郁闭度
    	List <Compartment> compartment = Compartment.find.where().eq("compartment", this).findList();
		Float canopyDensity = 0F;
		for( int i = 0; i < compartment.size(); i++ ){
			canopyDensity += compartment.get(i).canopyDensity()*compartment.get(i).area();
		}
		return canopyDensity/this.area();
    }
    
//    public SiteClass siteClass(){
//    	//地位级
//    }
    
    public Integer area(){
    	//计算面积
    	List <Compartment> compartment = Compartment.find.where().eq("compartment", this).findList();
    	int area = 0;
    	for( int i = 0; i < compartment.size(); i++){
    		area += compartment.get(i).area();
    	}
    	return area;
    }
}
